package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdTeamExpertgroup;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdTeamExpertgroupService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 专家 信息操作处理控制器
 * 
 * @author zhl
 * @date 2020-07-03 10:56:43
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "专家信息")
@RequestMapping("/qbdms/wQbdTeamExpertgroup")
public class WQbdTeamExpertgroupController extends SysBaseController{
	@Resource
	private WQbdTeamExpertgroupService wQbdTeamExpertgroupService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;


    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: zhl
     * @date: 2020-07-03 10:56:43
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到专家首页", exectype = "页面跳转日志")
    public String viewList(ModelMap modelMap,HttpServletRequest request) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdTeamExpertgroup/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询专家",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "createtime");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdTeamExpertgroup> pageDatas = wQbdTeamExpertgroupService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: zhl
     * @date: 2020-07-03 10:56:43
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到专家新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        // 上传附件类型相关
        String fileManagementUploadType = PropertyUtil.getByAlias("fileManagementUploadType", "");
        modelMap.put("fileManagementUploadType", fileManagementUploadType);
        String wjszsdsxlx = PropertyUtil.getByAlias("wjszsdsxlx", "");
        modelMap.put("wjszsdsxlx", wjszsdsxlx);
        return "wQbdTeamExpertgroup/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdTeamExpertgroup 保存的对象
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存专家数据",detail="<#if isAdd>新增<#else>编辑</#if>专家数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdTeamExpertgroup wQbdTeamExpertgroup) {
        String id = wQbdTeamExpertgroup.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdTeamExpertgroup.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdTeamExpertgroup);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.GROUPLEVEL.equals(currentSystemLevel)) {
                wQbdTeamExpertgroup.setReportStatus(ZhiLiangConst.GROUP_ADD);
            } else if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdTeamExpertgroup.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdTeamExpertgroup.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }

            result = wQbdTeamExpertgroupService.add(wQbdTeamExpertgroup);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            ZhiLiangConst.updateCommonFields(wQbdTeamExpertgroup);
            //修改操作
            result = wQbdTeamExpertgroupService.update(wQbdTeamExpertgroup);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdTeamExpertgroupService.getOneById(id), wQbdTeamExpertgroup));

        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到专家详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String isClose = RequestUtil.getString(request,"isClose");
        modelMap.put("id",id);
        modelMap.put("isClose",isClose);
        return "wQbdTeamExpertgroup/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询专家的一条数据",detail="根据主键id查询专家的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdTeamExpertgroup wQbdTeamExpertgroup = wQbdTeamExpertgroupService.getOneById(id);
        if (null == wQbdTeamExpertgroup) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdTeamExpertgroup);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除专家数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdTeamExpertgroup wQbdTeamExpertgroup = wQbdTeamExpertgroupService.getOneById(key);
            if (!userId.equals(wQbdTeamExpertgroup.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdTeamExpertgroup.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdTeamExpertgroup.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdTeamExpertgroup.getReportStatus()) && !ZhiLiangConst.GROUP_ADD.equals(wQbdTeamExpertgroup.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、待报集团的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdTeamExpertgroupService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到专家导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdTeamExpertgroup/import";
    }


    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到专家数据信息字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdTeamExpertgroup.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }



    /**
    * 功能描述: 导出专家数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: zhl
    * @date: 2020-07-03 10:56:43
    */
    @RequestMapping("/exportData")
    @Action(description="导出专家数据信息",detail="导出专家数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "CREATETIME");
            queryFilter.addFilter("orderSeq", "desc");
        }
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        List<WQbdTeamExpertgroup> wQbdTeamExpertgroups = this.wQbdTeamExpertgroupService.queryAll(queryFilter);
        if (wQbdTeamExpertgroups.isEmpty()) {
            wQbdTeamExpertgroups.add(new WQbdTeamExpertgroup());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdTeamExpertgroups, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    @Action(description = "导入专家数据信息", detail = "导入专家数据信息<#if success>成功<#else></#if>")
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;

                if ("idnumber".contains(fieldName)) {
                    returnType = new ReturnType();
                    boolean matches = fieldValue.matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$|^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)");
                    if (!matches) {
                        returnType.setMsg("身份证号格式不正确！");
                    } else {
                        returnType.setNewValue(fieldValue);
                    }
                }

                if ("mobile".contains(fieldName)) {
                    returnType = new ReturnType();
                    boolean matches = fieldValue.matches("(^1[3456789]\\d{9}$)");
                    if (!matches) {
                        returnType.setMsg("联系电话（手机）格式不正确，请输入正确的手机号码！");
                    } else {
                        returnType.setNewValue(fieldValue);
                    }
                }

//
                if ("tel".contains(fieldName)) {
                    returnType = new ReturnType();
                    boolean matches = fieldValue.matches("(^([0-9]{1,6}[-]?)?([0][1-9][0-9]{1,2}[-]?)?[0-9]{6,8}$)");
                    if (!matches) {
                        returnType.setMsg("座机格式不正确！");
                    } else {
                        returnType.setNewValue(fieldValue);
                    }
                }

                // 校验位置
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdTeamExpertgroup.class);
        String msg = map.get("msg").toString();
        List<WQbdTeamExpertgroup> list = (List<WQbdTeamExpertgroup>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdTeamExpertgroupService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }


    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        //业务数据
        List<WQbdTeamExpertgroup> reportList = wQbdTeamExpertgroupService.reportList(id, tableName);
        for (WQbdTeamExpertgroup wQbdAwardInformation : reportList) {
            try {
                // 上报状态显示名称
                wQbdAwardInformation.setReportStatusStr(ZhiLiangConst.getStatusStrByInt(wQbdAwardInformation.getReportStatus()));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }



}
